import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, setToken, getSingleToken,setSingleToken  } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

const w = []
// const w = ['/ecoCoord', '/ecoSlicing', '/ecoSuitable', '/affoTask', '/shrubWood', '/arborWood', '/ecoHomo']

const whiteList = ['/login', '/auth-redirect', '/bind', '/register', ...w]

router.beforeEach((to, from, next) => {
  NProgress.start()
  //  切换网页title
  if (to && to.meta && to.meta.pageTitle) {
    document.title = to.meta.pageTitle
  }

  // 如果cookie中存有token 或者 参数中带有token
  const querytoken = to.query.token
  if (getSingleToken() || querytoken) {

    // 取参数中的token更新store和cookie
    if (querytoken) {
      store.commit('SET_SINGLE_TOKEN', querytoken)
      setSingleToken(querytoken)
    }
    // 判断当前用户是否已拉取完user_info信息
    if (!store.getters.name) {
      store.dispatch('GetUserInfo').then(res => {
        // 登录本系统的获取token
        store.dispatch('Login', { username: 'admin', password: 'admin123' })
          .then(res => {
            next()
            NProgress.done()
          })
      }).catch(err => {
        // 获取用户信息失败  返回登录页
        window.location.href = `${process.env.VUE_APP_SINGLE_URL}?redirect=${window.location.origin}${window.location.pathname}`
        NProgress.done()
      })
    } else {
      next()
    }
  } else {
    // 返回登录页
    window.location.href = `${process.env.VUE_APP_SINGLE_URL}?redirect=${window.location.origin}${window.location.pathname}`
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done()
})
